package com.bracelet.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bracelet.config.CacheConfig;
import com.bracelet.mapper.*;
import com.bracelet.pojo.entity.*;
import com.bracelet.pojo.server.LocationDataReporting;
import com.bracelet.service.SaveMessageFormatService;
import com.bracelet.util.MessageFormatUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Component
@Slf4j
public class SaveMessageFormatServiceImp implements SaveMessageFormatService {

    @Autowired
    ICustomerInfoMapper customerInfoMapper;

    @Autowired
    LocationDataReportingMapper locationDataReportingMapper;
    @Autowired
    IBloodOxygenMapper iBloodOxygenMapper;
    @Autowired
    IBloodPresureMapper iBloodPresureMapper;
    @Autowired
    IBodyTemperatureMapper iBodyTemperatureMapper;
    @Autowired
    IHeartRateMapper iHeartRateMapper;

    @Autowired
    IDeviceInfoMapper iDeviceInfoMapper ;

    @Autowired
    IWarningListMapper iWarningListMapper;

    // 链路保持数据信息处理
    @Transactional
    @Override
    public ObjectNode exec(String seviceClass, String deviceInfo) throws Exception {
        String[] args = deviceInfo.split(",");
        LocationDataReporting locationDataReporting
                = (LocationDataReporting) MessageFormatUtil.formateObj(args,seviceClass);
        // 基本信息保存至设备表 IDeviceInfo  并记录至 信息表LocationDataReporting
        IDeviceInfo info = iDeviceInfoMapper.selectById(locationDataReporting.getDevideID());
        if(info == null){
            info = new IDeviceInfo();
            info.setDevideid(locationDataReporting.getDevideID());
            info.setLatitude(locationDataReporting.getLatitude());
            info.setLongitude(locationDataReporting.getLongitude());
            info.setStepcount(locationDataReporting.getStepCount());
            info.setInputtime(new Date());
            iDeviceInfoMapper.insert(info);
        }else{
            info.setLatitude(locationDataReporting.getLatitude());
            info.setLongitude(locationDataReporting.getLongitude());
            info.setStepcount(locationDataReporting.getStepCount());
            iDeviceInfoMapper.updateById(info);
        }
        // 处理一下经纬度 目前先卡济宁市
        dataAlarmVerification("jwd-jining","Latitude",locationDataReporting.getDevideID(),Double.parseDouble(locationDataReporting.getLatitude()));
        String idCard
                = dataAlarmVerification("jwd-jining","Longitude",locationDataReporting.getDevideID(),Double.parseDouble(locationDataReporting.getLongitude()));
        locationDataReportingMapper.insert(locationDataReporting);
        log.info("保存客户端信息成功"+locationDataReporting);
        return deviceReturnMessage("","");
    }

    // 心率处理类 [DW*334588000000156*0005*heart]
    @Transactional
    @Override
    public ObjectNode heart(String seviceClass, String deviceInfo) throws Exception {
        String[] args = deviceInfo.split(",");
        IHeartRate HeartRate
                = (IHeartRate) MessageFormatUtil.formateObj(args,seviceClass);

        IDeviceInfo info = iDeviceInfoMapper.selectById(HeartRate.getDevideid());
        if(info == null){
            info = new IDeviceInfo();
            info.setDevideid(HeartRate.getDevideid());
            info.setHeartrate(HeartRate.getHeartrate());
            info.setInputtime(new Date());
            iDeviceInfoMapper.insert(info);
        }else{
            info.setHeartrate(HeartRate.getHeartrate());
            iDeviceInfoMapper.updateById(info);
        }
        // 设备校验数据是否满足告警 记录信息
        String idCard
                = dataAlarmVerification("heartrate", "heartrate", HeartRate.getDevideid(), Double.parseDouble(HeartRate.getHeartrate()));
        HeartRate.setIdcard(idCard);
        iHeartRateMapper.insert(HeartRate);
        return  deviceReturnMessage(HeartRate.getDevideid(),"heart");
    }

    // 温度处理类  [DW*334588000000156*0004*temp]
    @Transactional
    @Override
    public ObjectNode temp(String seviceClass, String deviceInfo) throws Exception {
        String[] args = deviceInfo.split(",");
        IBodyTemperature bodyTemperature
                = (IBodyTemperature) MessageFormatUtil.formateObj(args,seviceClass);

        IDeviceInfo info = iDeviceInfoMapper.selectById(bodyTemperature.getDevideid());
        if(info == null){
            info = new IDeviceInfo();
            info.setDevideid(bodyTemperature.getDevideid());
            info.setBodytemperature(bodyTemperature.getBodytemperature());
            info.setInputtime(new Date());
            iDeviceInfoMapper.insert(info);
        }else{
            info.setBodytemperature(bodyTemperature.getBodytemperature());
            iDeviceInfoMapper.updateById(info);
        }
        double i = Double.parseDouble(bodyTemperature.getBodytemperature());
        String idCard
                = dataAlarmVerification("bodytemperature","bodytemperature",bodyTemperature.getDevideid(),i);
        bodyTemperature.setIdcard(idCard);
        iBodyTemperatureMapper.insert(bodyTemperature);
        return  deviceReturnMessage(bodyTemperature.getDevideid(),"temp");
    }

    // 血压处理类 [DW*334588000000156*0005*blood]
    @Transactional
    @Override
    public ObjectNode blood(String seviceClass, String deviceInfo) throws Exception {
        String[] args = deviceInfo.split(",");
        IBloodPressure bloodPressure
                = (IBloodPressure) MessageFormatUtil.formateObj(args,seviceClass);

        IDeviceInfo info = iDeviceInfoMapper.selectById(bloodPressure.getDevideid());
        if(info == null){
            info = new IDeviceInfo();
            info.setDevideid(bloodPressure.getDevideid());
            info.setDiastolicpressure(bloodPressure.getDiastolicpressure());
            info.setSystolicpressure(bloodPressure.getSystolicpressure());
            info.setInputtime(new Date());
            iDeviceInfoMapper.insert(info);
        }else{
            info.setDiastolicpressure(bloodPressure.getDiastolicpressure());
            info.setSystolicpressure(bloodPressure.getSystolicpressure());
            iDeviceInfoMapper.updateById(info);
        }
        dataAlarmVerification("bloodpressure","systolic",bloodPressure.getDevideid(),Double.parseDouble(bloodPressure.getSystolicpressure()));
        String idCard
                = dataAlarmVerification("bloodpressure","diastolic",bloodPressure.getDevideid(),Double.parseDouble(bloodPressure.getDiastolicpressure()));
        bloodPressure.setIdcard(idCard);
        iBloodPresureMapper.insert(bloodPressure);
        return  deviceReturnMessage(bloodPressure.getDevideid(),"blood");
    }

    // 血氧处理类 [DW*334588000000156*0006*oxygen]
    @Transactional
    @Override
    public ObjectNode oxygen(String seviceClass, String deviceInfo) throws Exception {
        String[] args = deviceInfo.split(",");
        IBloodOxygen  bloodOxygen
                = (IBloodOxygen) MessageFormatUtil.formateObj(args,seviceClass);
        IDeviceInfo info = iDeviceInfoMapper.selectById(bloodOxygen.getDevideid());
        if(info == null){
            info = new IDeviceInfo();
            info.setDevideid(bloodOxygen.getDevideid());
            info.setBloodoxygen(bloodOxygen.getBloodoxygen());
            info.setInputtime(new Date());
            iDeviceInfoMapper.insert(info);
        }else{
            info.setBloodoxygen(bloodOxygen.getBloodoxygen());
            iDeviceInfoMapper.updateById(info);
        }
        String idCard
                = dataAlarmVerification("bloodoxygen","bloodoxygen",bloodOxygen.getDevideid(),Double.parseDouble(bloodOxygen.getBloodoxygen()));
        bloodOxygen.setIdcard(idCard);
        iBloodOxygenMapper.insert(bloodOxygen);
        return  deviceReturnMessage(bloodOxygen.getDevideid(),"oxygen");
    }


    // 返回值处理类
    private ObjectNode deviceReturnMessage(String devideid,String key){
        ObjectMapper mapper = new ObjectMapper();
        ObjectNode objectNode = mapper.createObjectNode();
        objectNode.put("args","[DW*"+devideid+"*0006*"+key+"]");
        return objectNode;
    }

    /**
     * @param dictionary_code 校验字段
     * @param deviceId 设备编号
     * @param value 具体值
     * */
    private String  dataAlarmVerification(String dictionary_code,String remark,String deviceId,double value){
        DataDictionaryValue dictionaryValueByItem
                = CacheConfig.getDictionaryValueByItem(dictionary_code, remark);
        val values = dictionaryValueByItem.getValue().split("-");
        String warnName = dictionaryValueByItem.getName();
        Double lowerBound = Double.parseDouble(values[0]);
        Double upperBound  = Double.parseDouble(values[1]);


        ICustomerInfo c = new ICustomerInfo();
        QueryWrapper q = new QueryWrapper();
        q.eq("devideid",deviceId);
        ICustomerInfo iCustomerInfo = customerInfoMapper.selectOne(q);
        if(iCustomerInfo == null){
            log.info("{}未查询到匹配用户记录，不做预警数据登记",deviceId);
            return "";
        }

        IWarningList warningInfo = new IWarningList();
        if(lowerBound>value){
            // 低于下限
            warningInfo.setIdcard(iCustomerInfo.getIdcard());
            warningInfo.setStatus("N");
            warningInfo.setWarningtime(new Date());
            warningInfo.setDevideid(deviceId);
            warningInfo.setWarntype(warnName);
            warningInfo.setMessage(iCustomerInfo.getCustomername()+""+warnName+"过低！当前："+value);
        }else if(upperBound<value){
            // 高于上限
            warningInfo.setIdcard(iCustomerInfo.getIdcard());
            warningInfo.setStatus("N");
            warningInfo.setWarningtime(new Date());
            warningInfo.setDevideid(deviceId);
            warningInfo.setWarntype(warnName);
            warningInfo.setMessage(iCustomerInfo.getCustomername()+""+warnName+"过高！当前："+value);
        }else{
            // 正常
            log.info("{}本次采集{}数据信息正常",deviceId,dictionary_code);
            return iCustomerInfo.getIdcard();
        }
        iWarningListMapper.insert(warningInfo);
        return iCustomerInfo.getIdcard();
    }

}







